package com.jfire.socket.socketserver.interceptor.impl;

import com.jfire.baseutil.collection.ByteCache;
import com.jfire.baseutil.encrypt.AesUtil;
import com.jfire.socket.socketserver.bus.Message;
import com.jfire.socket.socketserver.bus.ServerChannelInfo;
import com.jfire.socket.socketserver.interceptor.MessageInterceptor;

public class AESEncryptIntercepror implements MessageInterceptor
{
    
    @Override
    public int getOrder()
    {
        return 1;
    }
    
    @Override
    public int inInterceptor(Message message)
    {
        ServerChannelInfo channelInfo = message.getChannelInfo();
        AesUtil aesUtil = new AesUtil(channelInfo.getKey());
        ByteCache businessData = message.getBusinessData();
        byte[] result = aesUtil.decrypt(businessData.toArray());
        businessData.clear().putArray(result);
        return MessageInterceptor.next;
    }
    
    @Override
    public int outInterceptor(Message message)
    {
        ServerChannelInfo channelInfo = message.getChannelInfo();
        ByteCache businessData = message.getBusinessData();
        AesUtil aesUtil = new AesUtil(channelInfo.getKey());
        byte[] result = aesUtil.encrypt(businessData.toArray());
        businessData.clear().putArray(result);
        return MessageInterceptor.next;
    }
    
}
